/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sdcache.distributed.client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;

/**
 * Socket Sender <br/>
 * Sends the tags in the outgoing queue to the Media Server
 * @author chaitanya
 */
public class Sender extends Thread
{

    private Socket socket;
    private ObjectOutputStream out;
    private BlockingQueue outQ;
    private ClientSocketInterface server;

    public Sender(String name, Socket socket, ClientSocketInterface server)
    {
        super(name + " Sender");
        this.socket = socket;
        this.server = server;
        outQ = server.getOutQ();
    }
    
    private void init()
    {
        try
        {
            out = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void run()
    {
        init();
        System.out.println("In sender run method");
        try
        {
            int count = 0;
            while (server.isRunning())
            {
                try
                {
                    while (server.isRunning() && outQ.size() > 0)
                    {
                        Object strTag = null;
                        strTag = outQ.take();


                        send(strTag);

                        count++;
                        if (count > 100)
                        {
                            count = 0;
                        }

                    }
                    try
                    {
                        Thread.sleep(100);
                    } catch (InterruptedException ie)
                    {
                    }
                } catch (Exception e)
                {
                //log.logMessage("SocketConnection","Sender::run() Exception : " + e.toString(),"Debug");
                //throw new Exception("From Sender");
                }
            }
        } catch (Exception e)
        {
            System.out.println(e);
        }
    }

    public void send(Object str) throws Exception
    {
        try
        {
            if (out != null)
            {
                //byte[] bytes = str.getBytes(); 
                //out.write(bytes, 0, bytes.length);
                out.writeObject(str);
                out.flush();
                                        System.out.println("------------------------ sent object");
            }
        } catch (Exception e)
        {
            System.out.println("Error : " + getName());
            throw e;

        }
    }
}
